//
//  JWPaintView.m
//  自作画板
//
//  Created by Jorn.Wu on 15/6/29.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "JWPaintView.h"
#import "JWPaintPath.h"

@interface JWPaintView ()
@property (nonatomic, strong) NSMutableArray *paths;
@property (nonatomic, strong) UIBezierPath *path;
@end

@implementation JWPaintView
- (void)setImg:(UIImage *)img{
    _img = img;
    //用接收的图片画图（渲染的时候要判断）
    [self.paths addObject:img];
    [self setNeedsDisplay];
}
- (NSMutableArray *)paths{
    if (_paths == nil) {
        _paths = [NSMutableArray array];
    }
    return _paths;
}
-(void)awakeFromNib{
    _lineWidth = 2;
}
- (CGPoint)pointWithTouches:(NSSet *)touches{
    UITouch *touch = [touches anyObject];
    return [touch locationInView:self];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    CGPoint startP = [self pointWithTouches:touches];
    //创建路径
    JWPaintPath *path = [JWPaintPath paintPathWithColor:_color lineWidth:_lineWidth startPoint:startP];
    _path = path;
    [self.paths addObject:path];
    
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    //获取触摸点
    CGPoint pos = [self pointWithTouches:touches];
    //确定终点
    [_path addLineToPoint:pos];
    //重绘
    [self setNeedsDisplay];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    if (!self.paths.count) {
        return;
    }
    
    for (JWPaintPath *path in self.paths) {
        if ([path isKindOfClass:[UIImage class]]) {
            UIImage *image = (UIImage *)path;
            [image drawAtPoint:CGPointZero];
//            [image drawInRect:self.frame];
        }else {
            [path.color set];//取出对应的颜色渲染对应的线
            [path stroke];
            
        }
        
    }
}
- (void)clearScreen{
    //清空所有路径
    [self.paths removeAllObjects];
    
    //重绘（刷新页面）
    [self setNeedsDisplay];
}
- (void)undo{
    [self.paths removeLastObject];//消除上一个路径
    [self setNeedsDisplay];
    
}
- (void)eraser{
    self.color = self.backgroundColor;
}


@end
